# -*- coding: utf-8 -*-

from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
from django import forms
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404, redirect
from django.core.mail import send_mail, BadHeaderError
from django.contrib.auth.forms import *
from django.db.models.query_utils import Q
from si_4k.sistema.models import *
from si_4k.sistema.forms import *
from django.contrib.auth.forms import *
from datetime import datetime
from django.contrib.auth.forms import PasswordChangeForm
from PIL import *
from django.contrib.auth.decorators import permission_required
from si_4k.py_docx.docx import *
from datetime import *
from django.core.servers.basehttp import FileWrapper
import os

#prefixo = ''
prefixo = '/home/edu4k/webapps/static_media/relatorios/'

def tabela_relatorio_aluno(request):
    ano_now = datetime.now()
    lista_alunos = Aluno.objects.all()
    return render_to_response('tabela_relatorio_aluno.html', locals(), context_instance=RequestContext(request))
    
def relatorio_aluno(request,id_aluno):
    #prefixo = ''
    prefixo = '/home/edu4k/webapps/static_media/relatorios/'
    
    try:
            os.remove(prefixo+aluno.nome+'.docx')
    except:
            pass
            
    # Default set of relationshipships - these are the minimum components of a document
    relationships = relationshiplist()
    
    # Make a new document tree - this is the main part of a Word document
    document = newdocument()
    
    # This xpath location is where most interesting content lives 
    docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
    
    # Append two headings and a paragraph
    
    data = datetime.now()
    data1 = data.day
    data2 = data.month
    data3 = data.year
    
    data_min = request.POST['data_inicio'+str(id_aluno)]
    data_split = data_min.rsplit('-')
    data_min = datetime(int(data_split[2]), int(data_split[1]), int(data_split[0]), 00,00)
    
    
    data_max = request.POST['data_fim'+str(id_aluno)]
    data_split = data_max.rsplit('-')
    data_max = datetime(int(data_split[2]), int(data_split[1]), int(data_split[0]), 23,59)
    
    lista = [['DATA', 'DURACAO', 'ATIVIDADE', 'LOCAL', 'VALOR HORA/AULA', 'VALOR TOTAL']]
    aluno = Aluno.objects.get(id = id_aluno)
    aluno.ultimo_relatorio = data.strftime("%d/%m/%y")
    aluno.save()
    
    lista_aulas = Aula.objects.filter(aluno = aluno).filter(inicio__gte=data_min).filter(inicio__lte=data_max).filter(valido=True)
    
    
    docbody.append(heading('''4K ASSESSORIA EDUCACIONAL E TREINAMENTOS''',1))
    docbody.append(heading('Aulas particulares - ' +str(data1) +  '/' +str(data2) + '/' +str(data3),2))
    
    docbody.append(heading('Aluno(a): '+aluno.nome,2))
    
    docbody.append(heading('Resumo de Aulas: ',2))
    
    soma = 0
    
    
    for aula in lista_aulas:
            
        inicio = aula.inicio
        fim = aula.fim
        delta = fim - inicio
        delta1 = delta.seconds/3600
        
        s = delta.seconds
        hours  = s / 3600
        s = s - (hours*3600)
        minutes = s/60
        seconds = s - (minutes*60)
        
        valor = aula.valor
        valor_total = valor * delta1
        soma += valor_total
        
        alunos = aula.aluno.all()
        cont = 0
        for aluno in alunos:
                cont = cont + 1
        if aula.local.nome == 'Casa do Aluno':
                if cont == 1:
                        atividade = 'Aula em Casa - Particular'
                else:
                        atividade = 'Aula em Casa - Grupo'
        else:
                if cont == 1:
                        atividade = 'Aula na 4K - Particular'
                else:
                        atividade = 'Aula na 4K - Grupo'
        
        lista.append([str(aula.inicio), str(delta1) + 'h'+str(minutes) + 'min', atividade , aula.local.nome , 'R$' + str(aula.valor), 'R$'+str(valor_total)])
    
    docbody.append(paragraph(''))
    docbody.append(table(lista))
    
    
    docbody.append(paragraph(''))

    docbody.append(heading('Valor final - R$'+str(soma) ,2))
    docbody.append(paragraph('Obs.: O pagamento pode ser efetuado via deposito bancario* ou em cheque/dinheiro na sede da 4K.'))
    
    docbody.append(paragraph(''))
    docbody.append(heading('Banco Itau (341)',2))
    docbody.append(paragraph(''))
    docbody.append(paragraph('Agencia: 0641'))
    docbody.append(paragraph('C/C: 78751-0'))
    docbody.append(paragraph('4K Assessoria Educacional e Treinamentos LTDA ME'))
    docbody.append(paragraph('CNPJ: 10.828.505/0001-00'))
    
    docbody.append(paragraph(''))
    docbody.append(paragraph('*Caso a forma de pagamento seja deposito em conta corrente,  por favor, faze-lo identificado ou enviar recibo para cordenacao@4keducacional.com.br'))
    
    docbody.append(paragraph('___________________________'))
    docbody.append(paragraph('Coordenacao'))
    docbody.append(paragraph(''))
    docbody.append(paragraph('4K Assessoria Educacional e Treinamentos LTDA - ME'))
    docbody.append(paragraph('CNPJ 10.828.505/0001-00'))
    
    
    
    
    # Create our properties, contenttypes, and other support files
    coreprops = coreproperties(title='Python docx demo',subject='A practical example of making docx from Python',creator='Mike MacCana',keywords=['python','Office Open XML','Word'])
    appprops = appproperties()
    global aluno_contenttypes
    global aluno_websettings
    global aluno_wordrelationships
    
    aluno_contenttypes = contenttypes()
    aluno_websettings = websettings()
    aluno_wordrelationships = wordrelationships(relationships)
    
    # Save our document
    savedocx(document,coreprops,appprops,aluno_contenttypes,aluno_websettings,aluno_wordrelationships,prefixo+'relatorio.docx')
    
    myfile = open(prefixo+'relatorio.docx', 'rb+')
    
    response = HttpResponse(FileWrapper(myfile), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename=relatorio.docx'
    
    return response

def aulas_aluno(request,id_aluno):
    aluno = Aluno.objects.get(id = id_aluno)
    lista_aulas = Aula.objects.filter(aluno = aluno)
    soma = 0
    for aula in lista_aulas:
        data_aula_inicio = aula.inicio
        data_aula_fim = aula.fim
        tempo = data_aula_fim - data_aula_inicio
        return HttpResponse(tempo.minutes)
    
    